<?php

/**
 * @author ahmedamdah
 *
 */

class XML {

	private $filename;
	private $xmlfile;

	/**
	 * @param string $_filename the xml file name
	 */
	function __construct($_filename)
	{
		$this->filename = $_filename;
	}

	/**
	 * @return string file name
	 */
	public function getfilename()
	{
		return $this->filename;
	}

	/**
	 * @param string $filename full path to file
	 */
	public function setfilename($filename)
	{
		$this->filename = $filename;
	}

	/**
	 *
	 * @return SimpleXMLElement
	 */
	public function get_xml_file()
	{
		return $this->xmlfile;
	}
	
	/**
	 * 
	 * @param SimpleXMLElement $xml_file
	 */
	public function set_xml_file($xml_file) {
		$this->xmlfile = $xml_file;
	}

	/**
	 * @return string
	 */
	public function getfiledir()
	{
		return realpath($this->filename);
	}
	


	/**
	 * this method allows to create a xml file with with the specified root element.
	 */
	public function createfile($rootElement)
	{
		$url = "http://www.w3.org/2001/XMLSchema-instance";
		$ficPath = "schemaPPAScript.xsd";
		$rootElement = "<!DOCTYPE cas SYSTEM 'dtdPPAScript.dtd'> <".$rootElement." xmlns:xsi=\"".$url."\" xsi:noNamespaceSchemaLocation=\"".$ficPath."\"/>";
		$this->xmlfile = new SimpleXMLElement($rootElement);
		$this->xmlfile->asXML($this->filename);
	}
	
	/**
	 * Loads a XML file into SimpleXMLElement. 
	 */
	public function load_file()
	{
		$this->xmlfile = simplexml_load_file($this->filename);
	}
	//consult the file with Xpath
	public function consulter($XPath)
	{
	$result = $this->xmlfile->xpath($XPath);
		while(list( , $node) = each($result)) {
				echo '<h4>',$node,'</h4>';
			}

	}
	public function nombreSituations($XPath)
	{
		$result = $this->xmlfile->xpath($XPath);
		$nodeCount = count($result); 
		return $nodeCount;
	}
	//delete the file
	public function deleteFile()
	{
		unlink($filename); 
	}

	/**
	 * Add a treenode to the specified SimpleXMLElement.
	 * @param treenode $node the treenode to add
	 * @param SimpleXMLElement $ElementParent the SimpleXMLElement witch @treenode will be added to.
	 */
	function add_node(treenode $node,SimpleXMLElement $ElementParent)
	{	
		
		//add childs
		$parent = $ElementParent->addChild($node->getname(),$node->getvalue());
		if($node->getattributes() != null)
		{
			foreach ($node->getattributes() as $attribute)
			{
				$parent->addAttribute($attribute->getname(), $attribute->getvalue());
			}
		}
		if($node->getchilds() != null)
		{
			foreach ($node->getchilds() as $childs)
			{	
				$this->add_node($childs,$parent);
			}
		}
		
		$this->xmlfile->asXML($this->filename);
	
	}
}
